<template>
  <el-dialog
    :title="title"
    class="gl_dialog_TitleLine"
    :visible.sync="dialogVisible"
    width="750px"
  >
    <div v-loading="dialogLoading">
      <div>
        <el-row>
          <el-col :span="11">
            <div class="transfer_wrap gl_mb_15">
              <div class="transfer_title gl_clear">
                <span class="gl_fl">必选成员</span>
              </div>
              <div class="transfer_content">
                <el-radio
                  v-if="mainMember.id"
                  v-model="currentMember"
                  :disabled="mainMember._select"
                  :label="mainMember"
                >
                  {{ mainMember.name }}
                  <span v-if="mainMember.genderCode === 'M'">(男)</span>
                  <span v-if="mainMember.genderCode === 'W'">(女)</span>
                </el-radio>
              </div>
            </div>
            <div class="transfer_wrap gl_mb_15">
              <div class="transfer_title gl_clear">
                <span class="gl_fl">可选成员</span>
              </div>
              <div class="transfer_content">
                <div v-for="(item, index) in leftList" :key="index" class="gl_mb_5">
                  <el-radio v-model="currentMember" :disabled="item._select" :label="item">
                    {{ item.name }}
                    <span v-if="item.genderCode === 'M'">(男)</span>
                    <span v-if="item.genderCode === 'W'">(女)</span>
                  </el-radio>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :offset="2" :span="11">
            <div v-for="(item, index) in rightList" :key="index" class="transfer_wrap gl_mb_15">
              <div class="transfer_btn_wrap" @click="changeMemberToRight(item)">
                <i class="transfer_btn el-icon-d-arrow-right" title="将选择的成员移至此处" />
              </div>
              <div class="transfer_title gl_clear">
                <span class="gl_fl">
                  {{ item.name }}
                </span>
                <span class="gl_fr">{{ item._children.length }}/1</span>
              </div>
              <div class="transfer_content">
                <div v-for="(jtem, jndex) in item._children" :key="jndex" class="gl_clear">
                  <span class="gl_fl">{{ jtem.name }}</span>
                  <span v-if="jtem.genderCode === 'M'">(男)</span>
                  <span v-if="jtem.genderCode === 'W'">(女)</span>
                  <i class="el-icon-close gl_pointer gl_fr" @click="removeMember(jtem, item, jndex)" />
                </div>
                <div v-if="!item._children.length" class="transfer_nodata">请选择成员</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-row class="gl_mt_15">
        <el-col v-if="teamEntry.teamEntryId" :span="12">
          <el-button type="danger" size="mini" @click="deleteGroup()">删除整组</el-button>
        </el-col>
        <el-col :span="teamEntry.teamEntryId ? 12 : 24" align="right">
          <el-button type="default" size="mini" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" size="mini" @click="submit()">确定</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: '成员选择'
    },
    ignoreCheck: {
      type: Boolean,
      default: false
    },
    minSelectMemberNum: {
      type: Number,
      default: 1
    },
    maxSelectMemberNum: {
      type: Number,
      default: 0
    },
    requireMember: {
      type: Object,
      required: true,
      default() {
        return {};
      }
    },
    optionMember: {
      type: Array,
      default() {
        return [];
      }
    },
    selectMember: {
      type: Array,
      default() {
        return [];
      }
    },
    teamEntry: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data () {
    return {
      dialogVisible: false,
      dialogLoading: false,
      currentMember: '',
      mainMember: {},
      leftList: [],
      rightList: []
    };
  },
  watch: {
    dialogVisible (val) {
      if (!val) {
        // 窗口关闭
        this.currentMember = '';
        this.mainMember = {};
        this.leftList = [];
        this.rightList = [];
      }
    }
  },
  methods: {
    // 打开
    open () {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.initData();
      });
    },
    close () {
      this.dialogLoading = false;
      this.dialogVisible = false;
    },
    hideLoading () {
      this.dialogLoading = false;
    },
    // 初始化数据，拷贝数据
    initData() {
      this.mainMember = JSON.parse(JSON.stringify(this.requireMember));
      const _optionMember = JSON.parse(JSON.stringify(this.optionMember)) || [];
      this.leftList = _optionMember.filter(item => item.id !== this.mainMember.id);
      this.rightList = JSON.parse(JSON.stringify(this.selectMember));
      this.matchMainMemberFromRightList();
    },
    // 从右侧列表中：匹配必选人员是否存在；匹配左侧列表是否存该人员
    matchMainMemberFromRightList () {
      for (let i = 0; i < this.rightList.length; i++) {
        const item = this.rightList[i];
        for (let j = 0; j < item._children.length; j++) {
          const jtem = item._children[j];
          const _jid = jtem.registerId || jtem.id;
          // 必选成员id
          const _mid = this.mainMember.registerId || this.mainMember.id;
          if (_mid === _jid) { // 找到了必选成员
            this.mainMember['_select'] = true;
          } else { // 非必选成员
            const findMember = this.leftList.find(ktem => {
              const _kId = ktem.registerId || ktem.id;
              return _kId === _jid;
            });
            if (findMember) { // 在左侧列表找到该人员
              findMember['_select'] = true;
            } else { // 在左侧列表没有找到该人员
              jtem['_select'] = true;
              this.leftList.push(jtem);
            }
          }
        }
      }
    },
    // 确认按钮
    submit() {
      let _isPass = false;

      if (this.ignoreCheck) {
        _isPass = this.checkChooseListPass();
      } else {
        _isPass = this.checkChooseListPass(true);
      }

      if (_isPass) {
        const _rightList = JSON.parse(JSON.stringify(this.rightList));
        this.dialogLoading = true;
        this.$emit('onTeamCompetitionSubmit', _rightList);
      } else {
        console.log('_isPass false: TeamCompetition Template');
      }
    },
    // 校验选择的成员是否符合要求
    checkChooseListPass (checkMemberNum) {
      let _hasMainMember = false;
      let _seleceMemberLen = 0;
      for (let i = 0; i < this.rightList.length; i++) {
        const item = this.rightList[i];
        if (item._children.length) {
          _seleceMemberLen++;
        }
        item._children.forEach(jtem => {
          const _jid = jtem.registerId || jtem.id;
          const _mid = this.mainMember.registerId || this.mainMember.id;
          if (_jid === _mid) {
            _hasMainMember = true;
          }
        });
      }

      if (checkMemberNum && _seleceMemberLen < this.minSelectMemberNum) {
        this.$message({
          message: `最少应分配${this.minSelectMemberNum}名成员`,
          type: 'warning',
          showClose: true
        });
        return false;
      }

      if (!_hasMainMember) {
        this.$message({
          message: `必选成员未被选择，所选成员中必须包含必选成员`,
          type: 'warning',
          showClose: true
        });
        return false;
      }

      return true;
    },
    // 移除右侧成员
    removeMember (jtem, container, jndex) {
      const _jId = jtem.registerId || jtem.id;
      if (this.mainMember.id === _jId) {
        // 说明移除的人员是必选人员
        this.mainMember['_select'] = false;
      } else {
        // 说明移除的人员是非必选人员
        jtem['_select'] = false;
      }
      container._children.splice(jndex, 1);
    },
    // 将所选成员移至右侧
    changeMemberToRight (container) {
      if (!this.currentMember) {
        this.$message({
          message: `请先选择要添加的成员`,
          type: 'warning',
          showClose: true
        });
        return;
      }

      if (container._children && container._children.length) {
        for (let i = 0; i < container._children.length; i++) {
          const item = container._children[i];
          const _iid = item.registerId || item.id;
          const _mid = this.mainMember.registerId || this.mainMember.id;
          if (_iid === _mid) {
            this.mainMember['_select'] = false;
          } else {
            item['_select'] = false;
          }
        }
      }
      this.currentMember['_select'] = true;
      container._children = [this.currentMember];
      this.currentMember = '';
    },
    deleteGroup () {
      this.$confirm(`您确定要删除整组吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(
          () => {
            this.dialogLoading = true;
            this.$emit('onDeleteGroupMember');
          }
        );
    }
  }
};
</script>

<style lang="scss" scoped>
.transfer_wrap {
  position: relative;
  width: 100%;
  border-radius: 4px;
  // overflow: hidden;
  border: 1px solid #ebebeb;
}
.transfer_title {
  width: 100%;
  height: 28px;
  padding: 0 10px;
  line-height: 28px;
  font-size: 13px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebebeb;
}
.transfer_content {
  padding: 10px;
  max-height: 260px;
  overflow-y: auto;
}
.transfer_btn {
  font-size: 24px;
  cursor: pointer;
  color: #1890ff;
  &:hover {
    color: #46a6ff;
  }
}
.transfer_btn_wrap {
  position: absolute;
  left: -35px;
  top: 16px;
  // margin-top: -16px;
}
.transfer_nodata {
  color: #c5c8ce;
  text-align: center;
}
</style>
